package com.lucy.scan.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.lucy.scan.params.ScanLoginParams;
import com.lucy.starter.constant.CommonConst;
import com.lucy.starter.constant.HttpStatus;
import com.lucy.starter.domain.ResponseDTO;
import com.lucy.starter.domain.vo.BaseUser;
import com.lucy.starter.loader.AuthService;
import com.lucy.starter.redis.RedisCache;
import com.lucy.starter.utils.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "鉴权系统")
@AllArgsConstructor
public class ScanLoginController {

    RedisCache redisCache;

    AuthService authService;

    @PostMapping("scanCheck")
    @ApiOperation(value = "扫码核查")
    public ResponseDTO<Object> scanCheck(@RequestBody @Validated ScanLoginParams params){
        // 1. 获取uuid
        String uuid = params.getUuid();
        // 2. 从缓存取出来
        String objStr = redisCache.getCacheObject(CommonConst.QR_CODE_KEY.concat(uuid));
        if (Validator.isEmpty(objStr)){
            return ResponseDTO.succMsg("未查询到信息");
        }else {
            Map<String,Object> loginRes = JsonUtil.string2Obj(objStr, Map.class);
            return ResponseDTO.succData(
                    loginRes
            );
        }
    }

    @PostMapping("scanLogin")
    @ApiOperation(value = "扫码登录")
    public ResponseDTO<Object> scanLogin(@RequestBody @Validated ScanLoginParams params){
        // 1. 获取当前登录用户信息
        if (!authService.isLogin()){
            return ResponseDTO.wrap(HttpStatus.UNAUTHORIZED,"请先登录");
        }
        // 2. 获取当前登录用户
        BaseUser user = authService.getUser();
        // 构建Map
        Map<String,Object> resMap = new HashMap<>(4);
        resMap.put("id",user.getUserId());
        resMap.put("userName",user.getUserName());
        resMap.put("nickName",user.getNickName());
        resMap.put("token",authService.getToken());
        redisCache.setCacheObject(CommonConst.QR_CODE_KEY.concat(params.getUuid()), JsonUtil.obj2String(resMap));
        return ResponseDTO.succMsg("扫码成功");
    }

}
